package cn.gov.cbrc.east.task;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.gov.cbrc.east.verify.ResultTotal;


/**
 * 项目名称：EastUpload<br>
 * *********************************<br>
 * <P>类名称：Schedule</P>
 * *********************************<br>
 * <P>类描述：工作调度安排</P>
 * 创建人：王川<br>
 * 创建时间：Oct 12, 2015 3:01:55 PM<br>
 * 修改人：王川<br>
 * 修改时间：Oct 12, 2015 3:01:55 PM<br>
 * 修改备注：<br>
 * @version 1.0<br>    
 */
public class Schedule {
	private static final Logger logger = LogManager.getLogger(Schedule.class);
	/** 主任务线程池 **/
	private static ExecutorService jobPool = Executors.newFixedThreadPool(10);
	private static List<FutureTask> futureTaskList = new ArrayList<FutureTask>();
	private static String taskId = "";
	private static List<File> taskFiles = new ArrayList<File>();
	public static void start(String fileName){
		try {
			if(fileName != null && !"".equals(fileName)){
				File dataFile = new File(fileName);
				getAllTaskFiles(dataFile);
			}
			//处理文件
			for(File file:taskFiles){
				file.getAbsoluteFile();
				FutureTask<ResultTotal> futureTask = new FutureTask<ResultTotal>(new Job(file.getAbsolutePath()));
				futureTaskList.add(futureTask);
				jobPool.execute(futureTask);
			}
			//获取结果
			while(futureTaskList.size()>=1){
				for(int i = 0;i<futureTaskList.size();i++){
					FutureTask task = futureTaskList.get(i);
					if(task.isDone()){
						ResultTotal result = (ResultTotal) task.get();
						taskId = result.getFileName()+".total";
						dealResult(result);
						futureTaskList.remove(task);
					}
				}
				Thread.sleep(500);
			}
		} catch (Exception e) {
			logger.info(e);
		}finally{
			JobLogFactory.stop(taskId);
			jobPool.shutdown();
		}
	}
	
	/**
	 * 获取目录下所有的txt文件（递归调用）
	 * @param file 文件或目录
	 */
	public static void getAllTaskFiles(File file){
		if(file.isFile()){
			taskFiles.add(file);
		}else if(file.isDirectory()){
			FilenameFilter filter = new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					File file = new File(dir+File.separator+name);
					if(name.toLowerCase().endsWith(".txt") || file.isDirectory()){return true;}else{return false;}
				}
			};
			File[] files = file.listFiles(filter);
			for(File f:files){
				getAllTaskFiles(f);
			}
		}else{
			logger.info("找不到"+file);
			return;
		}
	}
	
	/**
	 * 记录结果信息
	 * @param result
	 */
	public static void dealResult(ResultTotal result){
		StringBuffer sb = new StringBuffer();
		sb.append("文件名称："+result.getFileName());
		if(result.getErrorFields() > 0){
			sb.append("\r\n校验结果：错误");
		}else if(result.getErrorFields() == 0 && result.getWarningFields() > 0){
			sb.append("\r\n校验结果：警告");
		}else{
			sb.append("\r\n校验结果：正常");
		}
		sb.append("\r\n总行数："+result.getRow());
		sb.append("\r\n校验通过行数："+result.getSuccRows());
		sb.append("\r\n校验失败行数："+result.getFailRows());
		sb.append("\r\n用时："+result.getUsedTime()+"s");
		sb.append("\r\n说明："+result.getMessage());
		JobLogFactory.delete(taskId);
		Logger logger2 = JobLogFactory.createLogger(taskId);
		logger2.info(sb);
		logger.info(sb);
	}
	public static void main(String[] args) throws InterruptedException, ExecutionException{
		/*Schedule.start("C:\\BANKA-BHYWXXB-20150731.txt");*/
		if(args != null && args.length > 0){
			String file = args[0];
			Schedule.start(file.trim());
		}else{
			logger.info("请在运行命令后面添加文件名或目录！");
		}
	}
}
